package com.laxia.service;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import com.laxia.util.DateUtil;
import com.laxia.util.StringUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;

@Slf4j
@Getter
@Setter
@Service
public class IdGenerator {

    private long workerId = 0L;
    private long datacenterId = 0L;
    private static Snowflake snowflake;

    @PostConstruct
    void init() {
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
            log.info("当前机器 workerId: {}", workerId);
        } catch (Exception e) {
            log.warn("获取机器 ID 失败", e);
            workerId = NetUtil.getLocalhost().hashCode();
            log.info("当前机器 workerId: {}", workerId);
        }
        workerId = Math.abs(workerId % 32);
        snowflake = new Snowflake(workerId, datacenterId);
    }

    /**
     * 雪花算法生成的唯一ID 效率高 适合并发高的场景使用
     */
    public long nextId() {
        return snowflake.nextId();
    }

    /**
     * 雪花算法生成的唯一ID字符串形式 效率高 适合并发高的场景使用
     */
    public String nextIdStr() {
        return Long.toString(snowflake.nextId());
    }

    /**
     * 获取雪花算法ID生成时间
     */
    public Date getGenerateDateTime(long id) {
        try {
            return new Date(snowflake.getGenerateDateTime(id));
        } catch (Exception ignored) {

        }
        return null;
    }

    /**
     * 获取雪花算法ID生成时间
     */
    public String getGenerateDateTimeId() {
        try {
            String date = DateUtil.formatFullNumberDate(new Date());
            return date + StringUtil.randomNumber(5);
        } catch (Exception ignored) {

        }
        return null;
    }


}
